package com.zhao.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhao.bean.R;
import com.zhao.bean.User;
import com.zhao.dao.UserDao;
import com.zhao.service.UserService;
import com.zhao.utils.SMSUtils;
import com.zhao.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@RestController
public class UserController {

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserService userService;

    /**
     * 获取登录验证码
     *
     * @param user    用户
     * @param session 将用户的手机号和验证码传入session中
     * @return
     */
    @PostMapping("/user/sendMsg")
    public R sendMsg(@RequestBody User user, HttpSession session) {
        try {
            String phone = user.getPhone();
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            System.out.println("验证码：  " + code);

            /**
             * 调用阿里云短信api发送短信
             * SMSUtils.sendMessage("Reggin外卖", "欢迎使用reggin", phone, code);
             */

            session.setAttribute(phone, code);
            return R.success("验证码发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("验证码发送失败");
        }


    }

    /**
     * 验证登录
     *
     * @param params  前端传入的JSON字符串，包含号码和验证码
     * @param session 从session中取出前面存的验证码
     * @return
     */
    @GetMapping("/user/login/{params}")
    public R login(@PathVariable String params, HttpSession session) {

        Map map = JSON.parseObject(params, Map.class);
        String phone = (String) map.get("phone");
        String code = (String) map.get("code");
        String saveCode = (String) session.getAttribute(phone);

        if (saveCode.equalsIgnoreCase(code)) {
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone, phone);
            List<User> list = userDao.selectList(lqw);
            User user = new User();
            if (list.size() == 0) {
                user.setPhone(phone);
                user.setStatus(1);
                userDao.insert(user);
            } else {
                user = list.get(0);
            }
            session.setAttribute("user", user);
            return R.success("登录成功");
        } else {
            return R.error("登录失败");
        }
    }

}
